<template>
    <div>
        <el-page-header @back="goBack" :content="pageTitle"></el-page-header>
        <div class="common_line" style="margin-bottom: 10px;margin-top: 5px;"></div>
        <el-tabs v-model="activeName"  @tab-click="handleTabClick">
            <el-tab-pane label="组装单" name="join"></el-tab-pane>
            <el-tab-pane label="拆分单" name="split"></el-tab-pane>
        </el-tabs>
        <el-form ref="addForm" :model="addForm" label-width="auto">
            <el-row v-if="activeName=='join'">
                <el-col :span="24">
                    <el-form-item label="子件:" style="font-weight: bold;">
                        <div class="choose" @click="showChooseGoodAlert('join_sub')">选择商品</div>
                        <el-table :data="goods.zijians_zz" border style="width: 100%" :key="'join_sub_'+joinSubKey">
                            <el-table-column label="序号" align="center" width="60" prop="index" />
                            <el-table-column label="图片" align="center" width="80">
                                <template slot-scope="scope">
                                    <img v-if="scope.row.imgUrl" :src="scope.row.imgUrl" style="width: 55px;height: 55px;" alt="">
                                </template>
                            </el-table-column>
                            <el-table-column label="商品名称" min-width="100" align="center">
                                <template slot-scope="scope">
                                    <div style="cursor: pointer;color: #0099ff;" @click="showChooseGoodAlert('join_sub')">{{ scope.row.prod_name }}</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="商品编号" align="center" prop="goods_no" />
                            <el-table-column label="成本价" align="center" prop="unit_price_name" />
                            <el-table-column label="数量" align="center">
                                <template slot-scope="scope">
                                    <input class="inner_input" @blur="numBlur($event, scope.row, 'join_sub')" 
                                        style="width: 80px;" v-model="scope.row.num" placeholder="请输入">
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" width="60" align="center" prop="unit" />
                            <el-table-column label="规格" width="80" align="center" prop="specifications" />
                            <el-table-column label="金额" align="center" prop="total_price_name" />
                            <el-table-column label="库存剩余" min-width="80" align="center" prop="current_inventory_quantity" />
                            <el-table-column label="操作" min-width="80" align="center" class-name="small-padding fixed-width">
                                <template slot-scope="scope">
                                    <el-button
                                        size="mini"
                                        type="text"
                                        @click="handleAdd(scope.row, 'join_sub')"
                                        style="font-weight: bold;"
                                    >添加</el-button>
                                    <el-button
                                        size="mini"
                                        type="text"
                                        @click="handleRemove(scope.row, 'join_sub')"
                                        style="font-weight: bold;"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="组合件:" style="font-weight: bold;">
                        <div class="choose" @click="showChooseGoodAlert('join')">选择商品</div>
                        <el-table :data="goods.zuhes" border style="width: 100%" :key="'join_'+joinKey">
                            <el-table-column label="序号" align="center" width="60" prop="index" />
                            <el-table-column label="图片" align="center" width="80">
                                <template slot-scope="scope">
                                    <img v-if="scope.row.imgUrl" :src="scope.row.imgUrl" style="width: 55px;height: 55px;" alt="">
                                </template>
                            </el-table-column>
                            <el-table-column label="商品名称" min-width="100" align="center">
                                <template slot-scope="scope">
                                    <div style="cursor: pointer;color: #0099ff;" @click="showChooseGoodAlert('join')">{{ scope.row.prod_name }}</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="商品编号" align="center" prop="goods_no" />
                            <el-table-column label="成本价" align="center" prop="unit_price_name" />
                            <el-table-column label="数量" align="center">
                                <template slot-scope="scope">
                                    <input class="inner_input" @blur="numBlur($event, scope.row, 'join')" 
                                        style="width: 80px;" v-model="scope.row.num" placeholder="请输入">
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" width="60" align="center" prop="unit" />
                            <el-table-column label="规格" width="80" align="center" prop="specifications" />
                            <el-table-column label="金额" align="center" prop="total_price_name" />
                            <el-table-column label="库存剩余" min-width="80" align="center" prop="current_inventory_quantity" />
                            <el-table-column label="操作" min-width="80" align="center" class-name="small-padding fixed-width">
                                <template slot-scope="scope">
                                    <el-button
                                        size="mini"
                                        type="text"
                                        @click="handleRemove(scope.row, 'join')"
                                        style="font-weight: bold;"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row v-else>
                <el-col :span="24">
                    <el-form-item label="拆分件:" style="font-weight: bold;">
                        <div class="choose" @click="showChooseGoodAlert('split')">选择商品</div>
                        <el-table :data="goods.chaifens" border style="width: 100%" :key="'split_'+splitKey">
                            <el-table-column label="序号" align="center" width="60" prop="index" />
                            <el-table-column label="图片" align="center" width="80">
                                <template slot-scope="scope">
                                    <img v-if="scope.row.imgUrl" :src="scope.row.imgUrl" style="width: 55px;height: 55px;" alt="">
                                </template>
                            </el-table-column>
                            <el-table-column label="商品名称" min-width="100" align="center">
                                <template slot-scope="scope">
                                    <div style="cursor: pointer;color: #0099ff;" @click="showChooseGoodAlert('split')">{{ scope.row.prod_name }}</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="商品编号" align="center" prop="goods_no" />
                            <el-table-column label="成本价" align="center" prop="unit_price_name" />
                            <el-table-column label="数量" align="center">
                                <template slot-scope="scope">
                                    <input class="inner_input" @blur="numBlur($event, scope.row, 'split')" 
                                        style="width: 80px;" v-model="scope.row.num" placeholder="请输入">
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" width="60" align="center" prop="unit" />
                            <el-table-column label="规格" width="80" align="center" prop="specifications" />
                            <el-table-column label="金额" align="center" prop="total_price_name" />
                            <el-table-column label="库存剩余" min-width="80" align="center" prop="current_inventory_quantity" />
                            <el-table-column label="操作" min-width="80" align="center" class-name="small-padding fixed-width">
                                <template slot-scope="scope">
                                    <el-button
                                        size="mini"
                                        type="text"
                                        @click="handleRemove(scope.row, 'split')"
                                        style="font-weight: bold;"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="子件:" style="font-weight: bold;">
                        <div class="choose" @click="showChooseGoodAlert('split_sub')">选择商品</div>
                        <el-table :data="goods.zijians_cf" border style="width: 100%" :key="'split_sub_'+splitSubKey">
                            <el-table-column label="序号" align="center" width="60" prop="index" />
                            <el-table-column label="图片" align="center" width="80">
                                <template slot-scope="scope">
                                    <img v-if="scope.row.imgUrl" :src="scope.row.imgUrl" style="width: 55px;height: 55px;" alt="">
                                </template>
                            </el-table-column>
                            <el-table-column label="商品名称" min-width="100" align="center">
                                <template slot-scope="scope">
                                    <div style="cursor: pointer;color: #0099ff;" @click="showChooseGoodAlert('split_sub')">{{ scope.row.prod_name }}</div>
                                </template>
                            </el-table-column>
                            <el-table-column label="商品编号" align="center" prop="goods_no" />
                            <el-table-column label="成本价" align="center" prop="unit_price_name" />
                            <el-table-column label="数量" align="center">
                                <template slot-scope="scope">
                                    <input class="inner_input" @blur="numBlur($event, scope.row, 'split_sub')" 
                                        style="width: 80px;" v-model="scope.row.num" placeholder="请输入">
                                </template>
                            </el-table-column>
                            <el-table-column label="单位" width="60" align="center" prop="unit" />
                            <el-table-column label="规格" width="80" align="center" prop="specifications" />
                            <el-table-column label="金额" align="center">
                                <template slot-scope="scope">
                                    <div style="display: flex;align-items: center;">
                                        <span>￥</span>
                                        <input class="inner_input" style="width: 70px;" v-model="scope.row.total_price" placeholder="请输入">
                                    </div>
                                </template>
                            </el-table-column>
                            <el-table-column label="库存剩余" min-width="80" align="center" prop="current_inventory_quantity" />
                            <el-table-column label="操作" min-width="80" align="center" class-name="small-padding fixed-width">
                                <template slot-scope="scope">
                                    <el-button
                                        size="mini"
                                        type="text"
                                        @click="handleAdd(scope.row, 'split_sub')"
                                        style="font-weight: bold;"
                                    >添加</el-button>
                                    <el-button
                                        size="mini"
                                        type="text"
                                        @click="handleRemove(scope.row, 'split_sub')"
                                        style="font-weight: bold;"
                                    >移除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="12">
                    <el-form-item :label="activeName=='join'?'组装费用:':'拆分费用:'">
                        <el-input style="width: 240px" v-model="addForm.orders_fee" @blur="feeBlur" placeholder="请输入" maxlength="20" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="parseFloat(addForm.orders_fee)>0">
                    <el-form-item label="结算账户:" >
                        <el-select style="width: 240px;" v-model="addForm.pay_type" placeholder="请选择" clearable>
                            <el-option v-for="item in payTypes" :key="'pay_'+item.value" 
                                :label="item.label" :value="item.value"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="开单时间:" prop="expenditure_date">
                        <el-date-picker v-model="addForm.orders_date" type="date" format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                            style="width: 240px" placeholder="请选择" clearable>
                        </el-date-picker>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-if="isAdmin">
                    <el-form-item label="经办人:">
                        <div class="choose_border" @click="chooseHandlerUsers('handler')">
                            <span style="color: #c0c4cf;" v-if="!handler_name">请选择</span>
                            <span>{{ handler_name }}</span>
                            <!-- <i class="el-icon-circle-close icon" @click.stop="clearValue('handler')"></i> -->
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="12" v-else>
                    <el-form-item label="经办人:">
                        <div>{{ handler_name }}</div>
                    </el-form-item>
                </el-col>
                <el-col :span="20">
                    <el-form-item label="备注:">
                        <el-input maxlength="200" show-word-limit type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" v-model="addForm.remark" placeholder="请输入" clearable />
                    </el-form-item>
                </el-col>
            </el-row>

            <div style="font-size: 14px;font-weight: bold;height: 48px;line-height: 48px;margin-top: 10px;">上传附件</div>
            <el-row>
                <el-upload multiple ref="fileUpload" action="anything" :file-list="fileUploadList"
                    :http-request="(params) => uploadSectionFile(params)" :limit="5"
                    :on-preview="previewClick" :on-remove="(file) => removeFile(file)">
                    <el-button size="small" :disabled="canUpload" :class="canUpload?'btn_info_color':'btn_primary_color'" 
                        style="margin: 10px 0 0 40px;" icon="el-icon-upload2">上传附件</el-button>
                    <div slot="tip" class="el-upload__tip" style="margin-left: 20px;white-space:nowrap;display: inline-block;">
                        最多上传5个附件，单个附件大小限制在{{ max_file_size }}MB之内
                    </div>
                </el-upload>
            </el-row>
        </el-form>

        <bottom-btns
            Width="100%"
            MarginTop="30px"
            :buttons="buttonList"
            @superBtnClick="handleButtonClick"
        ></bottom-btns>

        <choose-product
            :showChooseProduct="showChooseGoods"
            :selectGoods="propGoods"
            :isMultiple="countMuti"
            @chooseOK="chooseOK"
            @hidden="showChooseGoods=false"
        ></choose-product>

        <!-- 选择经办人 -->
        <choose-user
            :showChooseUser="showChooseUserAlert"
            :selectUsers="selectedUsers.users"
            :title="selectedUsers.title"
            @chooseOK="chooseUserOK"
            @hidden="showChooseUserAlert=false"
        ></choose-user>
    </div>
</template>

<script>
import { getUserList } from "@/api/user";
import { listProduct } from '@/api/product';
import { addJoin, addSplit } from "@/api/joinsplit";
import bottomBtns from "@/components/bottomBtns";
import chooseProduct from "@/components/chooseProduct";
import chooseUser from "@/components/chooseUser";
import { baseUrl } from '@/config/env'
import { getToken } from '@/utils/auth'
const moment = require('moment')

export default {
    name: 'joinSplitEdit',
    components: {
        bottomBtns,
        chooseUser,
        chooseProduct
    },
    data() {
        return {
            showLoading: false,
            showChooseGoods: false,
            showChooseUserAlert: false,
            canUpload: false,
            userType: '',
            chooseGoodsType: 'join_sub',
            isAdmin: false,
            goods: {
                zijians_zz: [],
                zuhes: [],
                chaifens: [],
                zijians_cf: []
            },
            activeName: 'join',
            pageTitle: '',
            addForm: {
                corp: '',
                orders_fee: 0,
                orders_date: '',
                remark: '',
                handler_user: '',
                pay_type: '',
                file_id_list: [],
                goods: []
            },
            handler_name: '',
            joinKey: 0,
            splitKey: 0,
            splitSubKey: 0,
            joinSubKey: 0,
            handlersList: [],
            products: [],
            payTypes: [
                {label: '微信', value: 2},
				{label: '支付宝', value: 5},
				{label: '现金', value: 1},
				{label: '银行转账', value: 3},
				{label: '其他', value: 4}
            ],
            buttonList: [
                { name: '保存', type: 'commit', id:'1' },
                { name: '取消', type: 'cancel', id:'2' }
            ],
            fileUploadList: [],
            max_file_size: 10,  //最大可上传文件大小（MB）
        }
    },
    props: {
        corpId: {
            type: Number
        }
    },
    computed: {
        propGoods() {
            let goods = []
            if (this.chooseGoodsType == 'join_sub'){
                goods = this.goods.zijians_zz
            }else if (this.chooseGoodsType == 'join'){
                goods = this.goods.zuhes
            }else if (this.chooseGoodsType == 'split_sub'){
                goods = this.goods.zijians_cf
            }else if (this.chooseGoodsType == 'split'){
                goods = this.goods.chaifens
            }
            return goods
        },
        countMuti() {
            let falg = true
            if (this.chooseGoodsType == 'join' || this.chooseGoodsType == 'split'){
                falg = false
            }
            return falg
        },
        selectedUsers() {
            let users = []
            if (this.addForm.handler_user){
                users = [{id: this.addForm.handler_user}]
            }
            let title = '选择经办人'
            return {
                users, title
            }
        }
    },
    mounted() {
        this.addForm.corp = this.corpId
        this.isAdmin = this.$store.state.isAdmin
        this.handler_name = this.$store.state.userInfo.username
        this.addForm.handler_user = this.$store.state.userInfo.id
        this.addForm.orders_date = moment().format('yyyy-MM-DD')
        this.pageTitle = '新增组装单'
    },
    methods: {
        goBack() {
            this.$emit('hidden', '')
        },
        chooseHandlerUsers(type) {
            this.userType = type
            this.showChooseUserAlert = true
        },
        clearValue(type) {
            if (type == 'handler'){
                this.addForm.handler_user = ''
                this.handler_name = ''
            }
        },
        chooseUserOK(res) {
            if (this.userType == 'handler'){
                this.addForm.handler_user = res.length ? res[0].id : ''
                this.handler_name = res.length ? res[0].username : ''
            }
            this.showChooseUserAlert = false
        },
        handleTabClick(val) {
            console.log(val.name)
            this.pageTitle = this.pageTitle.substring(0, 2)+(val.name=='join'?'组装单':'拆分单')
        },
        showChooseGoodAlert(type) {
            this.chooseGoodsType = type
            this.showChooseGoods = true
        },
        chooseOK(data) {
            console.log(data)
            let goods = data.filter((item, index) => {
                item.index = index+1
                item.prod_name = item.name
                item.unit_price = item.unit_purchase_price?parseFloat(item.unit_purchase_price):0
                item.unit_price_name = '￥'+item.unit_price
                item.num = item.num?parseFloat(item.num):0
                item.total_price = this.$common.multiplyFloat(item.unit_price, item.num)
                item.total_price_name = '￥'+item.total_price 
                item.current_inventory_quantity = parseFloat(item.current_inventory_quantity)
                item.imgUrl = item.image_show?item.image_show.url:'https://anhuiyaoying.com/icon/default.png'
                return item
            })
            if (this.chooseGoodsType == 'join_sub'){
                this.goods.zijians_zz = goods
            }else if (this.chooseGoodsType == 'join'){
                this.goods.zuhes = goods
            }else if (this.chooseGoodsType == 'split_sub'){
                this.goods.zijians_cf = goods
            }else if (this.chooseGoodsType == 'split'){
                this.goods.chaifens = goods
            }
            this.$forceUpdate()
            this.showChooseGoods = false
        },
        handleAdd(row, type) {
            if (type == 'join_sub') {
                this.goods.zijians_zz.push({
                    index:this.goods.zijians_zz.length+1,imgUrl:'',prod_name:'',goods_no:'',unit_price:'',
                    num:'',unit:'',specifications:'',total_price:'',current_inventory_quantity:''
                })
            }else if (type == 'split_sub'){
                this.goods.zijians_cf.push({
                    index:this.goods.zijians_cf.length+1,imgUrl:'',prod_name:'',goods_no:'',unit_price:'',
                    num:'',unit:'',specifications:'',total_price:'',current_inventory_quantity:''
                })
            }
        },
        handleRemove(row, type) {
            function removeByIndexAndReindex(arr, indexToRemove) {
                // 使用 filter 方法过滤掉指定 index 的元素
                let newArray = arr.filter(item => item.index!== indexToRemove);
                // 遍历新数组，重新设置 index 属性
                for (let i = 0; i < newArray.length; i++) {
                    newArray[i].index = i + 1;
                }
                return newArray;
            }
            if (type == 'join_sub') {
                this.goods.zijians_zz = removeByIndexAndReindex(this.goods.zijians_zz, row.index)
            }else if (type == 'join'){
                this.goods.zuhes = []
            }else if (type == 'split_sub'){
                this.goods.zijians_cf = removeByIndexAndReindex(this.goods.zijians_cf, row.index)
            }else if (type == 'split'){
                this.goods.chaifens = []
            }
        },
        numBlur(val, row, type) {
            let value = val.target.value
            value = value.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
            const parts = value.split('.');
            if (parts.length > 2) {
                value = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }
            if (value > row.current_inventory_quantity){
                value = row.current_inventory_quantity
            }
            
            row.num = value
            row.total_price = this.subtractFloatMultiplication(row.unit_price, value).toFixed(2)
            row.total_price_name = '￥'+row.total_price
            if (type == 'join_sub') {
                // 使用 this.$set 强制刷新视图
                this.$set(this.goods.zijians_zz, this.goods.zijians_zz.indexOf(row), row); 
                this.joinSubKey++;
            }else if (type == 'join'){
                this.$set(this.goods.zuhes, this.goods.zuhes.indexOf(row), row); 
                this.joinKey++;
            }else if (type == 'split'){
                this.$set(this.goods.chaifens, this.goods.chaifens.indexOf(row), row); 
                this.splitKey++;
            }else if (type == 'split_sub'){
                this.$set(this.goods.zijians_cf, this.goods.zijians_cf.indexOf(row), row); 
                this.splitSubKey++;
            }
        },
        feeBlur(val) {
            let value = val.target.value
            value = value.replace(/[^0-9.]/g, ''); // 只允许数字和小数点
            const parts = value.split('.');
            if (parts.length > 2) {
                value = parts[0] + '.' + parts.slice(1).join(''); // 只取第一个小数点之前的部分
            }
            this.addForm.orders_fee = value?parseFloat(value):0
            if (value > 0){
                this.addForm.pay_type = 2
            }
        },
        // 浮点数计算 --- 相加
        subtractFloatPlus(a, b) {
            const factor = Math.pow(10, 2); // 乘以100来保留两位小数
            return (Math.round(a * factor) + Math.round(b * factor)) / 100;
        },
        // 浮点数计算 --- 相乘
        subtractFloatMultiplication(a, b) {
            const factor = Math.pow(10, 2); // 乘以100来保留两位小数
            return (Math.round(a * factor) * Math.round(b * factor)) / 10000;
        },
        getInfo() {
            
        },
        handleButtonClick(item) {
            switch (item.id) {
                case '1':   // 保存
                    this.commit()
                    break;
                case '2':   // 取消
                    this.goBack()
                    break;
            
                default:
                    break;
            }
        },
        commit() {
            var that = this
            let flag = false, msg = '';
            let zijian_zuhe_fee = this.goods.zijians_zz.reduce((accumulator, currentValue) => {
                return that.subtractFloatPlus(accumulator, currentValue.total_price)
            }, 0);
            let zijian_chaifen_fee = this.goods.zijians_cf.reduce((accumulator, currentValue) => {
                return that.subtractFloatPlus(accumulator, currentValue.total_price)
            }, 0);
            let zuhe_fee = that.goods.zuhes.length? parseFloat(that.goods.zuhes[0].total_price):0
            let chaifen_fee = that.goods.chaifens.length? parseFloat(that.goods.chaifens[0].total_price):0

            if (this.activeName == 'join'){
                this.goods.zijians_zz.some(item => {
                    if (!item.prod_name) {
                        flag = true
                        msg = '请选择子件商品！'
                        return true
                    }
                })
                if (!flag) {
                    this.goods.zuhes.some(item => {
                        if (!item.prod_name) {
                            flag = true
                            msg = '请选择组合件商品！'
                            return true
                        }
                    })
                }

                if (!flag && this.subtractFloatPlus(zijian_zuhe_fee, parseFloat(this.addForm.orders_fee)) != zuhe_fee){
                    flag = true
                    msg = '子件金额+组装费用不等于组合件金额！'
                }
            }else {
                this.goods.chaifens.some(item => {
                    if (!item.prod_name) {
                        flag = true
                        msg = '请选择拆分件商品！'
                        return true
                    }
                })
                if (!flag) {
                    this.goods.zijians_cf.some(item => {
                        if (!item.prod_name) {
                            flag = true
                            msg = '请选择子件商品！'
                            return true
                        }
                    })
                }

                if (!flag && this.subtractFloatPlus(chaifen_fee, parseFloat(this.addForm.orders_fee)) != zijian_chaifen_fee){
                    flag = true
                    msg = '拆分件金额+拆分费用不等于子件总金额，请调整各子件金额！'
                }
            }
            if (flag) {
                that.$message({
                    message: msg,
                    type: 'error'
                })
                return
            }

            let temp = null
            that.addForm.pay_type = !that.addForm.orders_fee?0:that.addForm.pay_type
            if (that.activeName == 'join') {
                this.addForm.goods = []
                this.goods.zijians_zz.forEach(item => {
                    that.addForm.goods.push({
                        goods_id: item.id,
                        num: item.num,
                        num_type: 2,  //出库
                        unit_price: item.unit_price,
                        total_price: item.total_price
                    })
                })
                this.addForm.goods.push({
                    goods_id: that.goods.zuhes[0].id,
                    num: that.goods.zuhes[0].num,
                    num_type: 1,  //入库
                    unit_price: that.goods.zuhes[0].unit_price,
                    total_price: that.goods.zuhes[0].total_price
                })
                temp = addJoin(that.addForm)
            }else{
                this.addForm.goods = []
                this.goods.zijians_cf.forEach(item => {
                    that.addForm.goods.push({
                        goods_id: item.id,
                        num: item.num,
                        num_type: 1,  //入库
                        unit_price: item.unit_price,
                        total_price: item.total_price
                    })
                })
                this.addForm.goods.push({
                    goods_id: that.goods.chaifens[0].id,
                    num: that.goods.chaifens[0].num,
                    num_type: 2,  //出库
                    unit_price: that.goods.chaifens[0].unit_price,
                    total_price: that.goods.chaifens[0].total_price
                })
                temp = addSplit(that.addForm)
            }

            temp.then(res => {
                if (res.code == 200){
                    that.$message({
                        message: '新增成功',
                        type: 'success'
                    })
                    that.$emit('success')
                }
            })
        },
        handlerGoodsChange(value, type) {
            let [ id, index ] = value.split('&&')
            let chooseItem = {}
            this.products.forEach(item => {
                if (item.id === Number(id)) {
                    chooseItem = item
                }
            })

            let that = this
            if (type == 'join_sub'){
                this.goods.zijians_zz.forEach(item => {
                    if (item.index === Number(index)) {
                        item.prod_name = chooseItem.name
                        item.num = 1
                        item.total_price = chooseItem.unit_price
                        item.total_price_name = '￥'+ chooseItem.unit_price
                        Object.assign(item, chooseItem)
                    }
                })
            }else if (type == 'join'){
                const sum = this.goods.zijians_zz.reduce((accumulator, currentValue) => {
                    return that.subtractFloatPlus(accumulator, currentValue.total_price)
                }, 0);
                
                this.goods.zuhes.forEach(item => {
                    if (item.index === Number(index)) {
                        item.prod_name = chooseItem.name
                        chooseItem.unit_price = sum
                        chooseItem.unit_price_name = '￥'+sum
                        item.num = 1
                        item.total_price = sum
                        item.total_price_name = '￥'+sum
                        Object.assign(item, chooseItem)
                    }
                })
            }else if (type == 'split_sub'){
                this.goods.zijians_cf.forEach(item => {
                    if (item.index === Number(index)) {
                        item.num = 1
                        item.total_price = chooseItem.unit_price
                        item.total_price_name = '￥'+ chooseItem.unit_price
                        item.prod_name = chooseItem.name
                        Object.assign(item, chooseItem)
                    }
                })
            }else if (type == 'split'){
                this.goods.chaifens.forEach(item => {
                    if (item.index === Number(index)) {
                        item.num = 1
                        item.total_price = chooseItem.unit_price
                        item.total_price_name = '￥'+ chooseItem.unit_price
                        item.prod_name = chooseItem.name
                        Object.assign(item, chooseItem)
                    }
                })
            }
            this.$forceUpdate()
            this.products = []
        },
        remoteMethodWithGoods(query, _index) {
            if (query !== '') {
                this.showLoading = true
                listProduct({
                    corp: this.addForm.corp,
                    search: query,
                    page: 1,
                    num: 999
                }).then(res => {
                    this.showLoading = false
                    this.products = res.data.data.good_list.filter(item => {
                        let cateName = item.category_name?('【'+item.category_name+'】'):''
                        item.label = cateName+item.name
                        item.value = item.id+'&&'+_index
                        item.unit_price = item.inventory_unit_price?parseFloat(item.inventory_unit_price):0
                        item.unit_price_name = '￥'+item.unit_price
                        item.current_inventory_quantity = parseFloat(item.current_inventory_quantity)
                        item.imgUrl = item.image_show?item.image_show.url:'https://anhuiyaoying.com/icon/default.png'
                        return item
                    });
                })
            } else {
                this.products = []
            }
        },
        // 选择经办人
        handlerPersonChange(value) {
            let [ id, username ] = value.split('&&')
            this.addForm.handler_user = id
            this.handler_name = username
        },
        remoteMethodWithHandler(query) {
            if (query !== '') {
                this.showLoading = true
                getUserList({
                    corp: this.addForm.corp,
                    username: query
                }).then(res => {
                    this.showLoading = false
                    this.handlersList = res.data.users.filter(item => {
                        item.label = item.username
                        item.value = item.id+'&&'+item.username
                        if (item.phone_no){
                            item.label += ('（'+item.phone_no+'）')
                        }
                        return item
                    });
                })
            } else {
                this.handlersList = []
            }
        },
        // ===================== 附件上传相关 ===========================
        // 上传前校验
        beforeUpload (file) {
            let isRightSize = file.size / 1024 / 1024 < this.max_file_size
            if (!isRightSize) {
                this.$message.error('文件大小超过' + this.max_file_size + 'MB')
            }
            // let fileArr = file.name.split('.')
            // let isAccept = new RegExp(this[uploadType].accept.join('|')).test('.' + fileArr[fileArr.length - 1])
            // if (!isAccept) {
            //     this.$message.error('请上传' + this[uploadType].accept.join(',') + '类型的文件')
            // }
            return isRightSize
        },
        // 自定义附件上传
        uploadSectionFile (params) {
            let _this = this
            if (!this.beforeUpload(params.file)) {
                params.onError()
                return
            }
            if (this.canUpload) return
             const loading = this.$loading({
                lock: true,
                text: '正在上传附件中，请稍后...'
            });
            _this.canUpload = true
            const formdata = new FormData()
            formdata.append('up_file', params.file)
            formdata.append('file_name', params.file.name)
            var xhr = new XMLHttpRequest();
            xhr.open("POST", baseUrl+'/upload_file/ali_oss_priv', true); //链接改成你项目中的
            xhr.setRequestHeader("TOKEN", getToken());  //令牌改成你项目中的
            xhr.setRequestHeader("CORP-ID", this.addForm.corp);  //令牌改成你项目中的
            xhr.send(formdata);
            xhr.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    var obj = JSON.parse(xhr.responseText); //返回值
                    _this.addForm.file_id_list.push(obj.data.id)
                    _this.fileUploadList.push({
                        name: obj.data.file_name,
                        url: obj.data.url_show,
                        id: obj.data.id
                    })
                    _this.$message.success('上传成功')
                    _this.canUpload = false
                    loading.close();
                }
            }
        },
        previewClick(file) {
            location.href = file.url
        },
        removeFile(file) {
            this.fileUploadList = this.fileUploadList.filter(item => item.id !== file.id)
            this.addForm.file_id_list = this.addForm.file_id_list.filter(item => item !== file.id)
        }
    }
}
</script>

<style lang="less" scoped>
    @import '../../../style/mixin.less';
    .inner_input {
        width: 100px;
        padding: 8px 5px;
    }
    .set_user_done {
        margin-left: 10px;
        font-size: 14px;
        &:hover {
            color: @blue;
            cursor: pointer;
        }
    }
    .choose {
        color: @blue;
        cursor: pointer;
        font-size: 14px;
        padding-left: 10px;
    }
    .set_user_none {
        margin-left: 10px;
        font-size: 14px;
        color: @blue;
        &:hover {
            cursor: pointer;
        }
    }
    .partner_view {
        .lists {
            height: 300px;
            overflow-y: auto;
            .cell {
                display: flex;
                border-bottom: 1px solid #eee;
                height: 40px;
                align-items: center;
                justify-content: space-between;
                .icon {
                    color: @blue;
                    font-size: 18px;
                }
            }
        }
    }
</style>

<style>
.el-upload-list__item {
    margin-left: 36px !important;
    width: calc(100% - 36px) !important;
}
</style>